<template>
  <div class="archive-container">
    <!-- 搜索与筛选区 -->
    <el-card shadow="hover">
      <el-form :inline="true">
        <el-form-item label="年份筛选">
          <el-select v-model="filter.year" clearable placeholder="请选择年份">
            <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year"
                :value="year"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="月份筛选">
          <el-select v-model="filter.month" clearable placeholder="请选择月份">
            <el-option
                v-for="month in monthOptions"
                :key="month.value"
                :label="month.label"
                :value="month.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分类筛选">
          <el-input v-model="filter.category" clearable placeholder="请输入分类">
            <el-option
                v-for="category in categoryOptions"
                :key="category"
                :label="category"
                :value="category"
            />
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据展示区 -->
    <el-card shadow="never" class="mt-4">
      <el-table
          :data="archives"
          stripe
          v-loading="loading"
          row-key="id"
      >
        <el-table-column prop="year" label="年份" width="100" />
        <el-table-column prop="month" label="月份" width="100">
          <template #default="{row}">
            {{ row.month }}月
          </template>
        </el-table-column>

        <el-table-column prop="title" label="文章标题" min-width="180">
          <template #default="{row}">
            <el-link :href="`/article/${row.id}`" target="_blank">
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column prop="category" label="分类" width="120" />

        <el-table-column prop="createdAt" label="发布时间" width="160" sortable>
          <template #default="{row}">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{row}">
            <el-button size="small" type="primary" @click="previewArticle(row.id)">预览</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控制 -->
      <el-pagination
          class="mt-4"
          :current-page="pagination.current"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '@/axios'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { fetchArticleDetail } from '@/api/admin/achive'

// 数据状态
const loading = ref(false)
const archives = ref([])

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 筛选条件
const filter = reactive({
  year: null,
  month: null,
  category: null
})

// 选项数据（需从接口获取）
const yearOptions = ref([2025])
const monthOptions = ref(
    Array.from({length:12}, (_,i) => ({
      value: `${i+1}`.padStart(2,'0'),
      label: `${i+1}月`
    }))
)


// 日期格式化工具函数
const formatDate = (dateStr) => {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm')
}

// 分页切换处理
const handlePageChange = (page) => {
  console.log('页码切换到:', page)
  pagination.current = page
  loadData()
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const params = {
      ...filter,
      page: pagination.current,
      pageSize: pagination.size
    }
    
    console.log('Current Page:', pagination.current)
    
    const { data } = await axios.get('/user/archives/list', { params })
    console.log('Request Params:', params)
    
    archives.value = data.records
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

// 重置筛选条件
const resetFilter = () => {
  Object.assign(filter, {
    year: null,
    month: null,
    category: null
  })
  loadData()
}

// 删除数据
const handleDelete = async (id) => {
  try {
    await axios.delete(`/user/archives/delete/${id}`);
    ElMessage.success('删除成功');
    loadData(); // 重新加载数据，确保前端同步更新
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// Update method to fetch article details before navigating
const previewArticle = async (articleId) => {
  try {
    const response = await fetchArticleDetail({ articleId });
    if (response.success) {
      const router = useRouter()
      router.push({ path: '/archives/detail', query: { articleId: articleId } });
    } else {
      ElMessage.error('Failed to fetch article details');
    }
  } catch (error) {
    ElMessage.error('Error fetching article details');
  }
};

// 初始化加载
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.archive-container {
  padding: 20px;
}
.mt-4 {
  margin-top: 1rem;
}
</style>
